import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Avatar,
  Upload,
  message,
  Tabs,
  Descriptions,
  Row,
  Col,
  Divider,
  Space,
  Tag,
  Modal,
  InputNumber,
} from 'antd';
import {
  UserOutlined,
  EditOutlined,
  CameraOutlined,
  SafetyOutlined,
  SettingOutlined,
  PhoneOutlined,
  MailOutlined,
  IdcardOutlined,
} from '@ant-design/icons';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { useAuth } from '../hooks/useAuth';
import { updateUserProfile, changePassword } from '../store/slices/authSlice';

// const { TabPane } = Tabs; // Deprecated, using items instead
const { TextArea } = Input;

interface ProfileFormData {
  username: string;
  email: string;
  phone: string;
  real_name: string;
}

interface PasswordFormData {
  old_password: string;
  new_password: string;
  confirm_password: string;
}

interface RiskAssessmentData {
  age: number;
  income_level: number;
  investment_experience: number;
  risk_tolerance: number;
  investment_goal: string;
}

const Profile: React.FC = () => {
  const dispatch = useAppDispatch();
  const { user } = useAuth();
  const { loading } = useAppSelector((state: any) => state.auth);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [riskForm] = Form.useForm();
  const [editMode, setEditMode] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [riskModalVisible, setRiskModalVisible] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');

  useEffect(() => {
    if (user) {
      form.setFieldsValue({
        username: user.username,
        email: user.email,
        phone: user.phone,
        real_name: user.real_name,

      });
      setAvatarUrl('');
    }
  }, [user, form]);

  const handleProfileUpdate = async (values: ProfileFormData) => {
    try {
      await dispatch(updateUserProfile(values)).unwrap();
      message.success('个人资料更新成功');
      setEditMode(false);
    } catch (error: any) {
      message.error(error || '更新失败');
    }
  };

  const handlePasswordChange = async (values: PasswordFormData) => {
    if (values.new_password !== values.confirm_password) {
      message.error('两次输入的密码不一致');
      return;
    }
    
    try {
      await dispatch(changePassword({
        old_password: values.old_password,
        new_password: values.new_password,
      })).unwrap();
      message.success('密码修改成功');
      setPasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (error: any) {
      message.error(error || '密码修改失败');
    }
  };

  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // 获取上传后的URL
      const url = info.file.response?.url || URL.createObjectURL(info.file.originFileObj);
      setAvatarUrl(url);
      message.success('头像上传成功');
    } else if (info.file.status === 'error') {
      message.error('头像上传失败');
    }
  };

  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    return true;
  };

  const getRiskLevelColor = (level: number) => {
    switch (level) {
      case 1: return 'green';
      case 2: return 'blue';
      case 3: return 'orange';
      case 4: return 'red';
      case 5: return 'purple';
      default: return 'default';
    }
  };

  const getRiskLevelText = (level: number) => {
    switch (level) {
      case 1: return '保守型';
      case 2: return '稳健型';
      case 3: return '平衡型';
      case 4: return '积极型';
      case 5: return '激进型';
      default: return '未评估';
    }
  };

  if (!user) {
    return <div>加载中...</div>;
  }

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={8}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ position: 'relative', display: 'inline-block' }}>
                <Avatar
                  size={120}
                  src={avatarUrl}
                  icon={<UserOutlined />}
                  style={{ marginBottom: '16px' }}
                />
                {editMode && (
                  <Upload
                    name="avatar"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={handleAvatarChange}
                    style={{
                      position: 'absolute',
                      bottom: '16px',
                      right: '0',
                    }}
                  >
                    <Button
                      type="primary"
                      shape="circle"
                      icon={<CameraOutlined />}
                      size="small"
                      style={{
                        position: 'absolute',
                        bottom: '16px',
                        right: '0',
                      }}
                    />
                  </Upload>
                )}
              </div>
              <h3>{user.real_name || user.username}</h3>
              <p style={{ color: '#666' }}>{user.email}</p>
              <Tag color={getRiskLevelColor(user.risk_level || 0)}>
                {getRiskLevelText(user.risk_level || 0)}
              </Tag>
            </div>
            <Divider />
            <Descriptions column={1} size="small">
              <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {new Date(user.created_at).toLocaleDateString()}
              </Descriptions.Item>
              <Descriptions.Item label="最后登录">
                {user.last_login ? new Date(user.last_login).toLocaleString() : '从未登录'}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
        
        <Col xs={24} lg={16}>
          <Card>
            <Tabs 
              defaultActiveKey="profile"
              items={[
                {
                  key: 'profile',
                  label: '基本信息',
                  children: (
                    <>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
                        <h3>个人资料</h3>
                        <Space>
                          {editMode ? (
                            <>
                              <Button onClick={() => setEditMode(false)}>取消</Button>
                              <Button type="primary" onClick={() => form.submit()} loading={loading}>
                                保存
                              </Button>
                            </>
                          ) : (
                            <Button type="primary" icon={<EditOutlined />} onClick={() => setEditMode(true)}>
                              编辑
                            </Button>
                          )}
                        </Space>
                      </div>
                      
                      <Form
                        form={form}
                        layout="vertical"
                        onFinish={handleProfileUpdate}
                        disabled={!editMode}
                      >
                        <Row gutter={16}>
                          <Col span={12}>
                            <Form.Item
                              label="用户名"
                              name="username"
                              rules={[{ required: true, message: '请输入用户名' }]}
                            >
                              <Input prefix={<UserOutlined />} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              label="真实姓名"
                              name="real_name"
                              rules={[{ required: true, message: '请输入真实姓名' }]}
                            >
                              <Input prefix={<IdcardOutlined />} />
                            </Form.Item>
                          </Col>
                        </Row>
                        
                        <Row gutter={16}>
                          <Col span={12}>
                            <Form.Item
                              label="邮箱"
                              name="email"
                              rules={[
                                { required: true, message: '请输入邮箱' },
                                { type: 'email', message: '请输入有效的邮箱地址' }
                              ]}
                            >
                              <Input prefix={<MailOutlined />} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              label="手机号"
                              name="phone"
                              rules={[
                                { required: true, message: '请输入手机号' },
                                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                              ]}
                            >
                              <Input prefix={<PhoneOutlined />} />
                            </Form.Item>
                          </Col>
                        </Row>

                      </Form>
                    </>
                  )
                },
                {
                  key: 'security',
                  label: '安全设置',
                  children: (
                    <>
                      <div style={{ marginBottom: '24px' }}>
                        <h3>安全设置</h3>
                      </div>
                      
                      <Card size="small" style={{ marginBottom: '16px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <div>
                            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                              <SafetyOutlined style={{ marginRight: '8px' }} />
                              <strong>登录密码</strong>
                            </div>
                            <div style={{ color: '#666' }}>定期更换密码可以提高账户安全性</div>
                          </div>
                          <Button onClick={() => setPasswordModalVisible(true)}>修改密码</Button>
                        </div>
                      </Card>
                      
                      <Card size="small">
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <div>
                            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                              <SettingOutlined style={{ marginRight: '8px' }} />
                              <strong>风险评估</strong>
                            </div>
                            <div style={{ color: '#666' }}>当前风险等级: 
                              <Tag color={getRiskLevelColor(user.risk_level || 0)} style={{ marginLeft: '8px' }}>
                                {getRiskLevelText(user.risk_level || 0)}
                              </Tag>
                            </div>
                          </div>
                          <Button onClick={() => setRiskModalVisible(true)}>重新评估</Button>
                        </div>
                      </Card>
                    </>
                  )
                }
              ]}
            />
          </Card>
        </Col>
      </Row>
      
      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        footer={null}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
        >
          <Form.Item
            label="当前密码"
            name="old_password"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password />
          </Form.Item>
          
          <Form.Item
            label="新密码"
            name="new_password"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>
          
          <Form.Item
            label="确认新密码"
            name="confirm_password"
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('new_password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setPasswordModalVisible(false);
                passwordForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                确认修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 风险评估模态框 */}
      <Modal
        title="风险评估"
        open={riskModalVisible}
        onCancel={() => {
          setRiskModalVisible(false);
          riskForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={riskForm}
          layout="vertical"
          onFinish={(values) => {
            // 这里可以添加风险评估逻辑
            console.log('Risk assessment:', values);
            message.success('风险评估已提交');
            setRiskModalVisible(false);
          }}
        >
          <Form.Item
            label="年龄"
            name="age"
            rules={[{ required: true, message: '请输入年龄' }]}
          >
            <InputNumber min={18} max={100} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            label="年收入水平（万元）"
            name="income_level"
            rules={[{ required: true, message: '请选择收入水平' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            label="投资经验（年）"
            name="investment_experience"
            rules={[{ required: true, message: '请输入投资经验' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            label="风险承受能力（1-5分）"
            name="risk_tolerance"
            rules={[{ required: true, message: '请评估风险承受能力' }]}
          >
            <InputNumber min={1} max={5} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            label="投资目标"
            name="investment_goal"
            rules={[{ required: true, message: '请描述投资目标' }]}
          >
            <TextArea rows={3} placeholder="请描述您的投资目标..." />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setRiskModalVisible(false);
                riskForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                提交评估
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile;